package com.kadron.dao;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.common.KUtil;
import com.kadron.entity.Item;

@AutoCreate
@BypassInterceptors
@Name("itemDAO")
public class KItemDAO extends KDAO<Item> {

	public Long getPrevNext(long itemId, boolean prev) {
		EntityManager em = getEntityManager();
		try {			
			return (Long) em.createQuery("SELECT e.id FROM Item e WHERE e.active=TRUE AND e.validFrom <= :moment AND e.validTo >= :moment AND e.id "+(prev?"<":">")+" :id ORDER BY e.id "+(prev?"DESC":"ASC"))
			.setParameter("id", itemId)
			.setParameter("moment", KUtil.getMoment())
			.setMaxResults(1)
			.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public Long getPrevNext(long itemId, long currencyId, boolean prev) {
		EntityManager em = getEntityManager();
		try {
			return (Long) em.createQuery("SELECT e.id FROM Item e WHERE e.active=TRUE AND e.validFrom <= :moment AND e.validTo >= :moment AND e.id "+(prev?"<":">")+" :id AND " +
						"EXISTS(SELECT 1 FROM Price p WHERE p.item.id=e.id AND p.currency.id=:cid AND p.price > 0) " +
						"ORDER BY e.id "+(prev?"DESC":"ASC"))
			.setParameter("id", itemId)
			.setParameter("moment", KUtil.getMoment())
			.setParameter("cid", currencyId)
			.setMaxResults(1)
			.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
}
